import { MD } from "../../GMDBase/MD"
import { gcfg } from "../../../gcfg"
import QWEventDispatcher from "../../GMDBase/QWEventDispatcher"
import QWEvent from "../../GMDBase/QWEvent"
import LCData from "../../GMDWeakNetGameBase/LCData";
import Login from "../../GMDWeakNetGameBase/Login";
import GameConn from "../../GMDWeakNetGameBase/GameConn";
import NSLoader from "../../GMDWeakNetGameBase/NSLoader";
import SDataShare from "./SDataShare"; 
import FB from "../FB";
import LocalResources from "../../GMDCocosBase/LocalResources";
import fbAccount from "../fbAccount";
import ShareUtil from "./ShareUtil";

/*
I16$ShareTarget	
0=无限制
1=个人和群（不区分群id）
2=个人和群（每个群单独记次）
3=仅群（不区分群id）
4-仅群（每个群单独记次）  
*/

let g_Shareing = false//当前是否处于分享中 
            
function WhenOpenShare(success:Function,fail:Function)
{
    
}

function GetShareImgAndText(row) {
    var imgBase64
    var title

    //存在重定向文案接口
    if (ShareMgr.RedirectImgAndText) {
        var obj = ShareMgr.RedirectImgAndText(row[SDataShare.Singletion.FD.I_ShareChannel])
        if (obj)//返回了重定向的文案
        {
            //返回的图片地址有效
            if (obj.imgUrl) imgBase64 = obj.imgBase64

            //返回的标题有效
            if (obj.title) title = obj.title
        }
    }

    //重定向失败时，应用原规则
    if (!imgBase64) 
    { 
    //imgUrl = StringEX.MergePath(MD.ServerList.ArticleSvr, row[SDataShare.Singletion.FD.I_Icon])
        imgBase64 = ShareUtil.getImgBase64(
             LocalResources.Singletion.GetRes( row[SDataShare.Singletion.FD.I_Icon] ).getTexture() 
             )
    }

    if (!title) title = row[SDataShare.Singletion.FD.I_Note]

    return {
        imgBase64: imgBase64,
        title: title
    }
}



//分享管理器
export default class ShareMgr {
    //分享错误事件
    public static EVT_SHARE_ERROR = "EvtShareError"

    public static RegParams()
    {
        var SyncStrParam = gcfg["SyncStrParam"]
        for (var shareChannel = 1; shareChannel <= 10; shareChannel++) {
            SyncStrParam["ShareGroup_" + shareChannel] = 1
            SyncStrParam["Share_" + shareChannel] = 1
        }
    }

    //分享管理器开始工作
    public static Go() {
       
        //追加需要同步的参数
        ShareMgr.RegParams()


        //注册需要日清的数据
        {
            for (var shareChannel = 1; shareChannel <= 10; shareChannel++) {
                MD.DailyRefresh.AddRefrishData("ShareGroup_" + shareChannel, "{}")//某个通道的群记次
                MD.DailyRefresh.AddRefrishData("Share_" + shareChannel, "0")
            }
        }
         
    }

    //主动弹出邀请
    public static OpenInvite(
        channelId: number, query: any = null
    )
    {
        cc.log("主动弹出邀请");
     
        if(!FB.InFB) return

        var row = SDataShare.Singletion.GetShareRow(channelId, 0)
        FB.logEvent(
            "all_invite_click",
            1,
            {type:row[SDataShare.Singletion.FD.I_LgType]}
        ) 
        
        var imgTxt = GetShareImgAndText(row)
        FBInstant.shareAsync({
         intent: 'SHARE',//
         image: imgTxt.imgBase64,
         text: imgTxt.title,
         data: query?query:{},
         }).then(() =>{
             console.log("邀请成功==============")
             // continue with the game.
         }).catch(
             (res) =>{
                 console.log("邀请失败==============",res)
             }   
         )
    }
  
    
    
    //主动弹出分享
    public static OpenShare(
        channelId: number, query: any = null
        ) 
    {
        cc.log("主动弹出分享");
     
        if(!FB.InFB) return

        var row = SDataShare.Singletion.GetShareRow(channelId, 0)
        FB.logEvent(
            "all_share_click",
            1,
            {type:row[SDataShare.Singletion.FD.I_LgType]}
        ) 
        
       
        //var imgTxt = GetShareImgAndText(row)
        cc.log("开始分享事件");
         

        g_Shareing = true

       // var queryStr = ShareMgr.Query2Str(query)
        //console.log("queryStr",queryStr);
        
      
        /*
        var fail = (res) => {
            if(!g_Shareing) return
            
            g_Shareing = false
            //errMsg 
            console.log("分享失败", res)

            if (
                res.errMsg != "shareAppMessage:fail cancel" &&
                res.errMsg != "shareAppMessage:cancel"
            )
                ShareMgr.PostErrorEvt(
                    channelId,
                    false,
                    ShareMgr.ERR_NO.UnknownError
                )
        }*/

        //WhenOpenShare(success,fail)

        /*
        wx.shareAppMessage(
            {
                withShareTicket: true,
                title: imgTxt.title,
                imageUrl: imgTxt.imgUrl,
                query: queryStr,
                success:success,
                fail:fail
            }
        );
        */
        
       FBInstant.context.chooseAsync({
         //filters: ['NEW_CONTEXT_ONLY'],
 //        minSize:2,
   //      maxSize:100,
       })
       .then((res)=> {
        console.log("选择好友成功！",res)
         //success(FBInstant.context)
         cc.log("成功选择了好友",FBInstant.context.getID());
         ShareMgr.postShare(channelId,FBInstant.context.getID(),query)
       })
       .catch(
           (res)=>{
               console.log("选择好友失败！",res)
               ShareMgr.DoShareFail(channelId)
           }
       )  
       
 
    }
 

    static DoShareFail(channelId:number)
    { 
        if(!g_Shareing) return
        
        g_Shareing = false
        //errMsg 
        console.log("分享失败")

        ShareMgr.PostErrorEvt(
            channelId,
            false,
            ShareMgr.ERR_NO.UnknownError
        )
    }
     

    static postShare(channelId:number,plyID:string,query: any )
    {
        var shareNum = ShareMgr.GetAllShareNum(channelId)
        var row = SDataShare.Singletion.GetShareRow(channelId, shareNum)

        var success = (res) => { 
            if(!g_Shareing) return
            FB.logEvent(
                "all_share_success",
                1,
                {type:row[SDataShare.Singletion.FD.I_LgType]}
            )
            g_Shareing = false 
            ShareMgr.DoShareSuccess(res, row)
        }

        /*
        if(query)
        {
            query["id"] = plyID
        }*/

        var imgTxt = GetShareImgAndText(row)
        FB.updateAsync({
            action: 'CUSTOM',
            cta: '',//Join The Fight
            image: imgTxt.imgBase64,
            text: {
              default: imgTxt.title,
              localizations: {
              //  ar_AR: 'X \u0641\u0642\u0637 \u063A\u0632\u062A ' +                '\u0642\u0631\u064A\u0629 Y!',
                //en_US: 'X just invaded Y\'s village!',
                //es_LA: '\u00A1X acaba de invadir el pueblo de Y!',
              }
            },
            template: 'VILLAGE_INVASION',
            data:  query?query:{},
            strategy: 'IMMEDIATE',
            notification: 'NO_PUSH',
          }).then(function() {
            // closes the game after the update is posted.
            //FBInstant.quit();
            success(FBInstant.context)
          }).catch(
            ()=>{
                console.log("向好友发送消息失败！")
                ShareMgr.DoShareFail(channelId)
            }
         )
    }

    //当前是否处于分享状态
    public static get Shareing(): boolean { return g_Shareing; }

    //重定向分享图文
    //入口参数: Func(shareChannel:number)
    //
    //重定向失败时，应返回 null
    //
    //重定向成功时候，应返回
    //{
    //    imgUrl:<图片地址>,
    //    title:<标题>
    //}
    public static RedirectImgAndText: Function

    //注册功能
    public static RegFunc(funcNum, func, owner = null) {
        ShareMgr.m_FuncCallbacks[funcNum] = [func, owner]
    }

    //错误号枚举
    public static ERR_NO = {
        MustShareToGroup: 0,//要求分享到群，实际却没有 
        TooMany: 2, //分享次数太多，已经没有奖励可领取了
        UnknownError: 3 //未知错误
        // RepeatedSharing：4
    };

    //监听事件
    public static addEventListener(type: string, listener, owner = null) {
        ShareMgr.m_Evts.addEventListener(type, listener, owner)
    }

    //参数对象转换为字符串形式
    static Query2Str(query: any): string {
        if (!query) return ""
        var re = ""
        for (var k in query) {
            var v = query[k]
            var str = k + "=" + v
            if (re == "")
                re = str
            else
                re += "&" + str
        }
        return re
    }


    //抛出错误事件
    static PostErrorEvt(channelId: number, isShareToGroup: boolean, errNo: number, exAttrs: any = null) {
        var evt = new QWEvent(ShareMgr.EVT_SHARE_ERROR)
        evt.details = {
            channelId: channelId,//分享口ID
            errNo: errNo,//错误号
            isShareToGroup: isShareToGroup,//用户实际是否是分享给群了
        }

        //填充扩展属性
        if (exAttrs) {
            for (var k in exAttrs) evt.details[k] = exAttrs[k]
        }

        ShareMgr.m_Evts.dispatchEvent(evt)
    }


    //执行功能
    static DoFunc(funcNum, obj: any) {
        var funcInfo = ShareMgr.m_FuncCallbacks[funcNum]
        if (!funcInfo) return

        if (funcInfo[1])//存在owner
            funcInfo[0].call(funcInfo[1], obj)
        else
            funcInfo[0](obj)
    }




    //执行分享成功的逻辑
    static DoShareSuccess(res, row) {
        cc.log("分享成功", res,res.getID())
        var isShareToGroup: boolean = false//res.shareTickets ? true : false//是否是分享到群
        var shareTarget = row[SDataShare.Singletion.FD.I_ShareTarget]
        var shareChannel = row[SDataShare.Singletion.FD.I_ShareChannel]
        if (
            (shareTarget == 3 || shareTarget == 4) &&//仅分享到群
            !isShareToGroup//实际没有分享到群
        ) { 
            cc.log("要求分享到群，实际却没有")
            ShareMgr.PostErrorEvt(
                shareChannel,
                isShareToGroup,
                ShareMgr.ERR_NO.MustShareToGroup
            )
            return
        }


        /*
        if (
            isShareToGroup &&//实际是分享到群的 
            (
                shareTarget == 2 || shareTarget == 4//需要区分群id  
            )
        ) {
            //获取群id
            for (var k in res.shareTickets) {
                var shareTicket = res.shareTickets[k]
                wx.getShareInfo(
                    {
                        shareTicket: shareTicket,
                        success: (res) => {
                            if (!MD.SessionKey)//当前没有获取到sessionKey
                            {
                                console.log("尚未登陆成功，无法解密数据")

                                ShareMgr.PostErrorEvt(
                                    shareChannel,
                                    isShareToGroup,
                                    ShareMgr.ERR_NO.UnknownError
                                )
                                return
                            }

                            //解密群id
                            var jsonDoc = Authorize.Decryption(res.encryptedData, res.iv, MD.SessionKey)
                            if (!jsonDoc) {
                                console.log("解密失败！")
                                ShareMgr.PostErrorEvt(
                                    shareChannel,
                                    isShareToGroup,
                                    ShareMgr.ERR_NO.UnknownError
                                )
                                return
                            }

                            var gid: string = jsonDoc.openGId

                            //执行分享成功功能
                            ShareMgr.DoShareFunc(shareTicket, gid, row)
                        },
                        fail: (res) => {
                            console.log("获取群信息失败", res)
                            ShareMgr.PostErrorEvt(
                                shareChannel,
                                isShareToGroup,
                                ShareMgr.ERR_NO.UnknownError
                            )
                        }
                    }
                )
            }

            return
        }
        */

        var shareTick = null
        /*
        if (res.shareTickets) {
            for (var kk in res.shareTickets) shareTick = res.shareTickets[kk]
        }*/
        
        //执行分享成功的功能
        ShareMgr.DoShareFunc(shareTick, null, row)
    }

    static DoShareFunc(shareTicket: string, groupId: string, row) {
        var isShareToGroup = shareTicket ? true : false
        var shareChannel = row[SDataShare.Singletion.FD.I_ShareChannel]
        var num = ShareMgr.GetShareNum(groupId, shareChannel)

        //检查是否需要重新根据次数选择行
        var NumType = row[SDataShare.Singletion.FD.I_NumType]//分享口类型
        if (NumType == 1)//根据分享次数
        {
            row = SDataShare.Singletion.GetShareRow(shareChannel, num)
        }

        var func = row[SDataShare.Singletion.FD.I_ShareFunc]

        //记录分享次数 
        num++

        var saveChannel = SDataShare.Singletion.GetSaveChannel(shareChannel) 

        if (groupId) {
            var scInfo = MD.LCData.GetJson("ShareGroup_" + saveChannel)
            scInfo[groupId] = num
            MD.LCData.SetJson("ShareGroup_" + saveChannel, scInfo)
        } else {
            MD.LCData.Set("Share_" + saveChannel, num)
        }

        var numOfTimes = SDataShare.Singletion.GetShareTotalNum(shareChannel)
        if (
            NumType == 1 &&//根据分享次数分享
            num > numOfTimes
        )
        { 
            ShareMgr.PostErrorEvt(
                row[SDataShare.Singletion.FD.I_ShareChannel],
                isShareToGroup,
                ShareMgr.ERR_NO.TooMany,
                {
                    numOfTimes: numOfTimes,//本日分享上限
                    dailyNum: num,//本日实际分享次数
                }
            )
            return
        }

        if (func > 0)//存在附加功能
        {
            if (isShareToGroup)//分享到群了
            {
                console.log("分享给群了") 
                ShareMgr.DoFunc(
                    func,
                    {
                        param: row[SDataShare.Singletion.FD.I_Param],//功能参数
                        dailyNum: num,//今日已经分享的次数
                        shareTicket: shareTicket,//群Ticket
                        groupId: groupId,//群ID
                    }
                )
            }
            else//分享到个人了
            { 
                console.log("分享给个人了 func=",func) 
                ShareMgr.DoFunc(
                    func,
                    {
                        param: row[SDataShare.Singletion.FD.I_ParamSingle],//功能参数
                        dailyNum: num,//今日已经分享的次数
                    }
                )
            }
        }
        else //无附加功能
        {
            cc.log("分享完成，无附加功能", shareChannel, shareTicket, num)
        }
    }

    //获取某个分享口实际已经分享的次数
    static GetShareNum(groupId: string, shareChannel: number): number {
        var saveChannel = SDataShare.Singletion.GetSaveChannel(shareChannel) 

        if (groupId) {
            var scInfo = MD.LCData.GetJson("ShareGroup_" + saveChannel)
            if (!scInfo[groupId]) return 0
            return scInfo[groupId]
        } else {
            return MD.LCData.GetNumber("Share_" + saveChannel)
        }
    }

    //获取某个分享口当日实际分享次数，个人加所有群
    static GetAllShareNum(shareChannel: number): number {
        var saveChannel = SDataShare.Singletion.GetSaveChannel(shareChannel) 
        var sum = MD.LCData.GetNumber("Share_" + saveChannel)
        var scInfo = MD.LCData.GetJson("ShareGroup_" + saveChannel)
        for (var k in scInfo) sum += scInfo[k]
        return sum
    }

    static m_FuncCallbacks: any = {}
    static m_PageShareRow: any
    static m_PageShareQuery: any
    static m_PageChannelSetup: boolean
    static m_PageChannelVisible: boolean
    static m_Evts: QWEventDispatcher = new QWEventDispatcher()
}

//页面分享口被点击
/*
if (window["wx"]) {
    wx.onShareAppMessage(
        () => {
            var row = ShareMgr.m_PageShareRow

            var imgTxt = GetShareImgAndText(row)

            g_Shareing = true

            var success = (res: any) => {
                if(!g_Shareing) return

                g_Shareing = false
                ShareMgr.DoShareSuccess(res, row)
            }
            var fail = (res: any) => {
                if(!g_Shareing) return

                g_Shareing = false
            }

            WhenOpenShare(success,fail)
            
            return {
                title: imgTxt.title,
                imageUrl: imgTxt.imgUrl,
                query: ShareMgr.Query2Str(ShareMgr.m_PageShareQuery),
                success:success,
                fail:fail
            }

        }
    )
}*/

//1号功能为加金币，直接实现在底层框架
ShareMgr.RegFunc(
    1,
    (obj: any) => {
        var currGold = MD.LCData.GetNumber(MD.LCData.ParamName.GOLD)
        MD.LCData.Set(MD.LCData.ParamName.GOLD, currGold + obj.param)
    }
)

MD.ShareMgr = ShareMgr